﻿using Infragistics.Controls.Grids;
using System.Collections;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Interactivity;

namespace Sidvall.UI.Wpf.Controls
{
    public class XamGridSelectedItemsBehavior : Behavior<XamGrid>
    {
        // Source: The XamGrid's SelectedRows collection
        // Target: The object bound as the behaviors SelectedItems collection
        private XamGrid Grid
        {
            get
            {
                return AssociatedObject as XamGrid;
            }
        }

        public INotifyCollectionChanged SelectedItems
        {
            get
            {
                return (INotifyCollectionChanged)GetValue(SelectedItemsProperty);
            }
            set
            {
                SetValue(SelectedItemsProperty, value);
            }
        }

        public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems", typeof(INotifyCollectionChanged),
            typeof(XamGridSelectedItemsBehavior), null);

        protected override void OnAttached()
        {
            base.OnAttached();

            Grid.SelectedRowsCollectionChanged += new System.EventHandler<SelectionCollectionChangedEventArgs<SelectedRowsCollection>>(Grid_SelectedRowsCollectionChanged);
        }

        void Grid_SelectedRowsCollectionChanged(object sender, SelectionCollectionChangedEventArgs<SelectedRowsCollection> e)
        {
            UnsubscribeFromEvents();

            TransferSourceToTarget(Grid.SelectionSettings.SelectedRows, this.SelectedItems as IList);

            SubscribeToEvents();
        }

        private void SubscribeToEvents()
        {
            Grid.SelectedRowsCollectionChanged += new System.EventHandler<SelectionCollectionChangedEventArgs<SelectedRowsCollection>>(Grid_SelectedRowsCollectionChanged);
        }

        private void UnsubscribeFromEvents()
        {
            Grid.SelectedRowsCollectionChanged -= new System.EventHandler<SelectionCollectionChangedEventArgs<SelectedRowsCollection>>(Grid_SelectedRowsCollectionChanged);
        }

        public static void TransferSourceToTarget(IList source, IList target)
        {
            if (source == null || target == null)
                return;

            target.Clear();

            foreach (Row r in source)
            {
                // make sure we only take data rows from the root band
                if (r.RowType == RowType.DataRow && r.ParentRow == null)
                {
                    target.Add(r.Data);
                }
            }
        }
    }
}
